package day03;

/*
 * Author: JacksonCoder
 * FileName: reflectDemo
 * Version: 1.0.0
 * Date: 2025/4/10
 */

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

class Person{
    private String name;

    public Person(){
        this.name = "Default";
    }

    public Person(String name) {
        this.name = name;
    }

    public void sayHello(){
        System.out.println("Hello, my name is " + name);
    }

    private void secretMethod(){
        System.out.println("This is a secret method!");
    }

}

public class reflectDemo {
    public static void main(String[] args) throws Exception{
        // 1.获取 User 类的 Class 对象
        Class<?> clazz = Class.forName("day03.Person");

        // 2. 创建对象（调用无参构造函数）
        Object obj = clazz.getDeclaredConstructor().newInstance();

        // 3. 调用公开方法 sayHello()
        Method method = clazz.getMethod("sayHello");
        method.invoke(obj); // 输出: Hello, my name is Default

        // 4. 调用私有方法 secretMethod()
        Method secret = clazz.getDeclaredMethod("secretMethod");
        secret.setAccessible(true); // 打破私有访问限制
        secret.invoke(obj);

        // 5. 使用构造器创建对象（传参）
        Constructor<?> constructor = clazz.getConstructor(String.class);
        Object user2 = constructor.newInstance("Nexora");
        Method method2 = clazz.getMethod("sayHello");
        method2.invoke(user2);
    }
}
